#!/usr/bin/env python

from subprocess import Popen, PIPE
import sys, os
import pygtk,pygst
pygtk.require('2.0') # Make sure user has pygtk atleast version 2
import gtk,gst
import re 

class Main():
    
    def killApp(self, widget, data=None):
            print "Application terminated"
            gtk.main_quit() # Quit application
     
    # Changes record button back to Record when recording ends
    def clickedRecord(self,widget):
        if self.btnRecord.get_label() == "Record":
            self.setFilename()
            self.record()
            self.btnRecord.set_label("Stop Recording")
        else:
            self.record()
            self.btnRecord.set_label("Record")       
        
    # Set filename of the new voice recording
    def setFilename(self):
        self.filename = self.recordFileName.get_text()
        print "New Recording: %s saved!"%self.filename    
        
    # Calls bash script to record voice using 'arecord'        
    def record(self):
        # Calls bash record command
        if self.btnRecord.get_label() == "Record":
            
            # Start recording
            print "Recording started..."
            id = Popen("arecord -d 30 -q -r 22050 -t wav ./%s.wav"%self.filename, shell = True)
            self.processID = id.pid
            
        else:
            # Stop recording
            print "Recording stopped"
            Popen("kill %d"%self.processID, shell = True)
    
    def __init__(self):
        
        # Main frame
        self.frame = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.frame.set_position(gtk.WIN_POS_CENTER) # Center App
        self.frame.set_size_request(300,100)
        self.frame.set_tooltip_text("Dialogue Creator") # Hover over main frame
        
        # Exit button
        self.btnExit = gtk.Button("EXIT")
        self.btnExit.connect("clicked", self.killApp)
        self.btnExit.set_tooltip_text("Exit the application")
        
        # Choose wave file
        self.btnWaveFile = gtk.FileChooserButton("Choose file", None)
        self.btnWaveFile.set_title("Open Recording...")
        
        # Stop/Start wave file
        self.playback = gtk.Button("Play")
        self.playback.connect("clicked", self.play_stop_wave)
        
        # Record voice
        self.btnRecord = gtk.Button("Record")
        self.btnRecord.connect("clicked", self.clickedRecord)
        
        # Textbox
        self.labelFileName = gtk.Label("Enter the name of the new recording.")
        self.recordFileName = gtk.Entry()
        self.recordFileName.connect("activate", self.setFilename)
        self.recordFileName.set_text("NewRecording")
        
        # Horizontal box
        self.hbox1 = gtk.HBox()
        self.hbox1.pack_start(self.btnWaveFile)
        self.hbox1.pack_start(self.playback)
        self.hbox1.pack_start(self.btnExit)
        
        # Label and entry box
        self.vbox2 = gtk.VBox()
        self.vbox2.pack_start(self.labelFileName)
        self.vbox2.pack_start(self.recordFileName)
        
        # Record button and filename entry box
        self.hbox2 = gtk.HBox()
        self.hbox2.pack_start(self.vbox2)
        self.hbox2.pack_start(self.btnRecord)
        
        # Vertical box
        self.vbox = gtk.VBox()
        self.vbox.pack_start(self.hbox1)
        self.vbox.pack_start(self.hbox2)
        
        # Details 
        self.frame.set_title("Dialogue Creator 2012 - SE206 Assignment 3")
        self.frame.add(self.vbox)
        self.frame.show_all() # Make all elements visible
        self.frame.connect("destroy", self.killApp) # Kill App when closed
        
        # Wave player
        self.player = gst.element_factory_make("playbin2", "player")
        fakesink = gst.element_factory_make("fakesink", "fakesink")
        self.player.set_property("video-sink", fakesink)
        bus = self.player.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.on_message)
    
    def play_stop_wave(self, w):
        if self.playback.get_label() == "Play":
            filepath = self.btnWaveFile.get_filename() # Extract file name
            if os.path.isfile(filepath): # Check file exists
                self.playback.set_label("Stop")
                # Set uri to the one selected by the user
                self.player.set_property("uri", "file://" + filepath)
                # Play the .wav file
                self.player.set_state(gst.STATE_PLAYING)
        else:
            # Stop player
            self.player.set_state(gst.STATE_NULL)
            self.playback.set_label("Play")
                  
    def on_message(self, bus, message):
        t = message.type
        if t == gst.MESSAGE_EOS:
            self.player.set_state(gst.STATE_NULL)
            self.playback.set_label("Play")
        elif t == gst.MESSAGE_ERROR:
            self.player.set_state(gst.STATE_NULL)
            err, debug = message.parse_error()
            print "Error: %s" % err, debug
            self.playback.set_label("Play")
            
    def main(self):
        gtk.main() # Run the main method of GTK
    
if __name__ == "__main__":
    base = Main()
    base.main()
    
    

    
    
